package com.example.everying.controller.content;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.everying.context.UserContext;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.entity.content.ActivityAudit;
import com.example.everying.model.entity.content.ActivityComment;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.content.ActivityCommentVo;
import com.example.everying.service.content.ActivityArticleService;
import com.example.everying.service.content.ActivityCommentService;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.CampusException;
import com.example.everying.utils.QueryLocationUtil;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @program: everything
 * @description: 评论管理
 * @author: zw
 * @create: 2025-05-19 10:08
 **/
@Slf4j
@RestController
@Api(tags = "评论管理")
@RequestMapping("/activity/comment")
public class ActivityCommentController {

    @Autowired
    private ActivityCommentService commentService;
    @Autowired
    private ActivityArticleService articleService;

    @Autowired
    private QueryLocationUtil queryLocationUtil;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "添加评论")
    @PostMapping("addComment")
    public Result addComment(@RequestBody ActivityCommentVo commentVo) {

        ActivityComment comment = new ActivityComment();
        BeanUtil.copyProperties(commentVo, comment);
        if (ObjectUtil.isNotEmpty(commentVo.getId())) {
            //设置双亲ID
            comment.setParentId(commentVo.getId());
        }
        String cid = commentVo.getArticleId();
        ActivityAudit audit = articleService.getByCid(cid);

        if (audit.getStatus() == 0) {
            return Result.fail().message("此信息在审核中，禁止评论");
        }
        if (audit.getStatus() == 2) {
            return Result.fail().message("此信息已下架，禁止评论");
        }
        commentService.addComment(comment);


        return Result.ok("评论成功");
    }

//    @ApiOperation(value = "删除发表评论")
//    @DeleteMapping("{commentId}")
//    public ResponseEntity<Object> delComment(@PathVariable String commentId) {
//        UserEntity user = UserContext.getUser();
//        try {
//            // 检查评论是否存在
//            if (commentService.getById(commentId).getId().isEmpty()) {
//                return ResponseEntity.notFound().build();
//            }
//            // 执行删除操作
//            commentService.removeById(commentId);
//            // 返回成功响应
//            return ResponseEntity.ok().build();
//        } catch (Exception e) {
//            // 处理异常
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("删除评论失败: " + e.getMessage());
//        }
//    }

    /**
     * 评论删除逻辑
     *
     * @param commentId
     * @return
     */
    @DeleteMapping("/{commentId}")
    @Transactional
    public Result<ResponseEntity<?>> deleteComment(@PathVariable String commentId) {
        try {
            // 获取当前用户
            UserEntity user = UserContext.getUser();
            if (user == null) {
                return Result.success(ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body("用户未登录"));
            }
            // 获取评论信息
            ActivityComment comment = commentService.getById(commentId);
            if (comment == null) {
                return Result.success(ResponseEntity.notFound().build());
            }
            // 检查删除权限
            if (!checkDeletePermission(comment, user.getId())) {
                return Result.success(ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body("没有删除权限"));
            }
            // 删除评论及其关联数据
            commentService.deleteCommentWithRelations(commentId);
            return Result.success(ResponseEntity.ok().build());
        } catch (Exception e) {
            log.error("删除评论失败: commentId={}", commentId, e);
            return Result.success(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("删除评论失败"));
        }
    }

    /**
     * 获取评论数据和权限
     *
     * @param articleId
     * @return
     */
    @GetMapping("/{articleId}/comments")
    public ResponseEntity<List<ActivityCommentVo>> getCommentsByArticleId(@PathVariable String articleId) {
        ActivityArticle article = articleService.getById(articleId);
        if (article == null) {
            throw new CampusException("文章已被删除", 201);
        }
        // 获取当前用户
        UserEntity user = UserContext.getUser();
        // 获取评论列表
        List<ActivityCommentVo> comments = commentService.getCommentsByArticleId(articleId);

        // 转换为VO并设置权限
        List<ActivityCommentVo> commentVOs = comments.stream()
                .map(comment -> convertToVO(comment, user.getId()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(commentVOs);
    }

    public ActivityCommentVo convertToVO(ActivityComment comment, String userId) {
        ActivityCommentVo vo = new ActivityCommentVo();
        // 复制基本属性
        BeanUtils.copyProperties(comment, vo);
        // 设置删除权限
        vo.setCanDelete(checkDeletePermission(comment, userId));
        // 递归转换子评论
        if (comment.getChildren() != null && !comment.getChildren().isEmpty()) {
            List<ActivityCommentVo> childrenVOs = comment.getChildren().stream()
                    .map(child -> convertToVO(child, userId))
                    .collect(Collectors.toList());
            vo.setChildren(childrenVOs);
        } else {
            vo.setChildren(new ArrayList<>());
        }
        return vo;
    }

    private boolean checkDeletePermission(ActivityComment comment, String userId) {
        if (userId == null) {
            return false;
        }
        // 1. 评论作者本人可以删除
        if (userId.equals(comment.getUserId())) {
            return true;
        }
        ActivityArticle byId = articleService.getById(comment.getArticleId());
//         2. 文章作者可以删除
        if (userId.equals(byId.getUserId())) {
            return true;
        }
        // 3. 管理员可以删除
        UserEntity user = UserContext.getUser();
        if (user != null
                && (user.getIsAdministrator() == 1 || user.getIsAdministrator() == 3)) {
            return true;
        }
        return false;
    }


    /**
     * 创建评论
     *
     * @param comment
     * @return
     */
    @PostMapping("/addCom")
    public Result<ActivityComment> createComment(@RequestBody ActivityComment comment, HttpServletRequest request) {
        return Result.success(commentService.saveComment(comment, request));
    }

    /**
     * 创建回复
     *
     * @param commentId
     * @param reply
     * @return
     */
    @PostMapping("/{commentId}/replies")
    public ActivityComment createReply(@PathVariable String commentId, @RequestBody ActivityComment reply) {
        return commentService.saveReply(commentId, reply);
    }

    /**
     * 获取文章评论
     *
     * @param articleId
     * @return
     */
    @GetMapping("/articles/{articleId}")
    public List<ActivityComment> getCommentsByArticle(@PathVariable String articleId) {
        return commentService.getCommentsByArticle(articleId);
    }

    /**
     * 获取评论的回复
     *
     * @param commentId
     * @return
     */
    @GetMapping("/{commentId}/replies")
    public List<ActivityComment> getRepliesByComment(@PathVariable String commentId) {
        return commentService.getRepliesByComment(commentId);
    }

    /**
     * 获取评论的数据
     *
     * @param articleId
     * @return
     */
    @GetMapping("/{articleId}")
    public List<ActivityCommentVo> getByArticle(@PathVariable String articleId) {
        return commentService.getCommentsByArticleId(articleId);
    }

    /**
     * 判断评论是否已被删除
     *
     * @param commentId 评论ID
     * @return Result<Boolean> true表示已删除，false表示未删除
     */
    @ApiOperation(value = "判断评论是否已删除")
    @GetMapping("/isDeleted/{commentId}")
    public Result<Boolean> isCommentDeleted(@PathVariable String commentId) {

        ActivityComment comment = commentService.getById(commentId);
        // 如果评论为null，说明已被删除
        if (comment == null) {
            return Result.success(true);
        }
        return Result.success(comment.getIsDelete() == 1);

    }

}

